<?php

namespace App\Kuafu\Shop\Service\DouyinSelfLibrary;

use App\Kuafu\Wechat\Enum\WechatCodeEnum;
use App\Kuafu\Wechat\Exceptions\WechatException;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;

class DouyinSelfService extends DouyinSelfBaseService
{


    /**
     * 登录凭证校验
     * @param string $code
     * @param string $appid
     * @return array
     * @throws GuzzleException
     * @throws WechatException
     */
    public static function AuthCodeToSession(string $code, string $appid): array
    {
        Log::channel('douyinSelf')->info('用户登录授权抖音请求数据：' . json_encode(['code' => $code, 'appId' => $appid]));

        try {
            $result = (new DouyinSelfBaseService)->codeToSession($code);
            Log::channel('douyinSelf')->info('用户登录授权抖音返回数据：', $result);
            if (isset($result['err_no']) && $result['err_no'] != 0) {
                throw new WechatException(WechatCodeEnum::APPID_ERROR);
            }
            return $result['data'];
        } catch (\Exception $exception) {
            throw new WechatException(WechatCodeEnum::ERR_SERVER_ERROR, $exception->getMessage());
        }

    }


    /**
     * 解密
     * @param $encryptedData
     * @param $iv
     * @param $sessionKey
     * @param int $shopId
     * @return false|string
     */
    public static function decryptData($encryptedData, $iv, $sessionKey, int $shopId = 0)
    {
        $appId = (new DouyinSelfBaseService)->getClientKey();
        $data  = ['data' => $encryptedData, 'iv' => $iv, 'key' => $sessionKey, 'appid' => $appId];
        Log::channel('douyinSelf')->info('解密原始数据:' . json_encode($data));
        if (strlen($sessionKey) != 24) {
            throw new WechatException(WechatCodeEnum::ILLEGAL_AES_KRY);
        }
        $aesKey = base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            throw new WechatException(WechatCodeEnum::ILLEGAL_IV);
        }
        $aesIV     = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result    = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj   = json_decode($result);
        if ($dataObj == null) {
            Log::channel('douyinSelf')->error("解密错误信息：" . openssl_error_string());
            throw new WechatException(WechatCodeEnum::ILLEGAL_BUFFER);
        }
        if ($dataObj->watermark->appid != $appId) {
            throw new WechatException(WechatCodeEnum::ILLEGAL_BUFFER_APPID);
        }
        return $result;
    }

    /**
     * 用户券列表 查询
     * @param string $openId 抖音用户open_id
     * @param string $poiId 适用门店poi_id
     * @param int $page 分页展示用户券起始页，默认1
     * @param int $size 分页查询订单数量 page_size <= 50，默认50
     * @return mixed
     * @throws GuzzleException
     */
    public function getUserCertificatesList(
        string $openId,
        string $poiId = '',
        int $page = 1,
        int $size = 50
    ) {
        $bizParam = [
            'page'       => $page,
            'page_size'  => $size,
            'account_id' => DouyinSelfBaseService::ACCOUNT_ID,//商家团购账号id（抖音来客账号id）。需要先有此商家授权关系才能获取到。
            'open_id'    => $openId,
        ];
        if ($poiId) {
            $bizParam['poi_id'] = $poiId;// 适用门店poi_id
        }
        $response = $this->doCurl('/api/trade/v2/fulfillment/query_user_certificates/', $bizParam, 'post');

        $format = self::commonReturn($response);
        return $format['oriData'];
    }

    /**
     * 查询订单可用门店
     * @param string $orderId 抖音内部交易订单号，长度<64
     * @param string $poiId 适用门店poi_id
     * @return mixed
     * @throws GuzzleException
     */
    public function getOrderCanUse(string $orderId, string $poiId = '')
    {
        $bizParam = [
            'order_id' => $orderId,
            'biz_type' => 1,// 业务类型，1核销工具，2外卖。核销工具可默认不传。
        ];
        if ($poiId) {
            $bizParam['poi_id'] = $poiId;// 适用门店poi_id
        }
        $response = $this->doCurl('/api/trade/v2/fulfillment/order_can_use/', $bizParam, 'post');

        $format = self::commonReturn($response);
        return $format['oriData'];
    }


}
